package com.ash.nio.udp.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

public class DatagramChannelServerDemo {

    private static ByteBuffer buf = ByteBuffer.allocate(1024);

    private static Selector selector;

    public static void main(String[] args) throws Exception {
        DatagramChannel dc = DatagramChannel.open();
        dc.configureBlocking(false);
        dc.socket().bind(new InetSocketAddress(71));

        selector = Selector.open();
        dc.register(selector, SelectionKey.OP_READ);

        while (true) {
            selector.select();

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey eventKey = it.next();
                if (eventKey.isAcceptable()) {
                    handleAccept(eventKey);

                } else if (eventKey.isReadable()) {
                    handleRead(eventKey);

                } else if (eventKey.isWritable()) {
                    handleWrite(eventKey);
                }

                it.remove();
            }
        }

    }

    private static void handleAccept(SelectionKey eventKey) throws Exception {
        System.out.println("server connect...");
    }

    private static void handleRead(SelectionKey eventKey) throws IOException {
        System.out.println("server read...");

        DatagramChannel dc = (DatagramChannel) eventKey.channel();
        buf.clear();

        SocketAddress address = dc.receive(buf);
        String clientAddress = address.toString().replace("/", "").split(":")[0];
        String clientPost = address.toString().replace("/", "").split(":")[1];

        buf.flip();

        String content = "";
        while (buf.hasRemaining()) {
            // read 1 byte at a time
            buf.get(new byte[buf.limit()]);
            content += new String(buf.array());
        }

        System.out.println(address + "接收的消息：" + content);

        // 将消息回送给客户端
        ByteBuffer buf3 = ByteBuffer.allocate(65507);
        buf3.clear();
        buf3.put(content.getBytes());
        buf3.flip();
        dc.send(buf3, new InetSocketAddress(clientAddress, Integer.parseInt(clientPost)));
    }

    private static void handleWrite(SelectionKey eventKey) {
        System.out.println("server write...");
    }

}
